package top.hcode.hoj.config;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.*;
import com.fasterxml.jackson.databind.module.SimpleModule;
import org.nutz.lang.Times;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.Date;

/**
 * @author orangej
 * @since 2024/12/17
 */
@Configuration
public class JacksonConfig {
    @Bean
    public MappingJackson2HttpMessageConverter objectMapper() {
        ObjectMapper objectMapper = new ObjectMapper();


        SimpleModule module = new SimpleModule();

        // 解析定制
        module.addDeserializer(Date.class, new DateDeserializer()); // 设置日期格式

        // 输出定制
        module.addSerializer(BigDecimal.class, new BigDecimalSerializer());
        module.addSerializer(Date.class, new DateSerializer());

        objectMapper.registerModule(module);

        // 忽略null
        objectMapper.setDefaultPropertyInclusion(JsonInclude.Include.NON_NULL);

        // 忽略反序列化时的未知属性
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);

        return new MappingJackson2HttpMessageConverter(objectMapper);
    }

    public static class DateDeserializer extends JsonDeserializer<Date> {
        @Override
        public Date deserialize(JsonParser jsonParser, DeserializationContext deserializationContext) throws IOException, JsonProcessingException {
            String date = jsonParser.getText();
            try {
                return Times.D(date);
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        }
    }

    public static class DateSerializer extends JsonSerializer<Date> {

        @Override
        public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (date == null) {
                jsonGenerator.writeNull();
            } else {
                jsonGenerator.writeString(Times.sDT(date));
            }
        }
    }

    public static class BigDecimalSerializer extends JsonSerializer<BigDecimal> {


        @Override
        public void serialize(BigDecimal decimal, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
            if (decimal == null) {
                jsonGenerator.writeNull();
            } else {
                jsonGenerator.writeNumber(decimal.stripTrailingZeros().toPlainString());
            }
        }
    }
}
